package gw.com.android.ui.onlive.analyst;

import android.text.TextUtils;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;

import gw.com.android.model.ConfigType;
import gw.com.android.model.ConfigUtil;
import gw.com.android.presenter.http.ChatTokenRequest;
import gw.com.android.presenter.http.HttpCallback;
import gw.com.android.presenter.http.Https;
import gw.com.android.utils.CacheUtils;
import okhttp3.Request;
import okhttp3.Response;
import www.com.library.app.Logger;

/**
 * @author jett
 * @since 2018-06-06.
 */
public class AnalystRequest {

    public AnalystData fetchLocal(String userNo, String accountNo) {
        String key = !TextUtils.isEmpty(accountNo) ? accountNo : userNo;
        String result = CacheUtils.readFile(getCacheFile(key));
        return parse(result, key, false);
    }

    public void getInfo(final String userNo, final String accountNo, final HttpCallback<AnalystData> callback) {
        new ChatTokenRequest().acquire(new ChatTokenRequest.OnTokenListener() {
            @Override
            public void onSuccess(String token) {
                requestInfoByAccountNo(userNo, token, callback);
            }

            @Override
            public void onFailure(Exception e) {
                if (callback != null) {
                    callback.onFailure(e);
                }
            }
        });

    }

    private void requestInfoByUserNo(final String userNo, String token, final HttpCallback<AnalystData> callback) {
        String url = ConfigUtil.instance().getHttpUrlIp(ConfigType.CHAT_URL_TAG) + "/api/user/getUserInfoByUserNo";
        new Https(url)
                .addParam("userNo", userNo)
                .addParam("appsecret", ConfigUtil.instance().mConfigObject.optString(ConfigType.CHAT_APPSECRET))
                .addParam("token", token)
                .get(new Https.ResponseCallback<String>() {
                    @Override
                    public void onSuccess(Request request, Response response, String result, int code) {
                        AnalystData data = parse(result, userNo, true);
                        if (callback != null) {
                            callback.onSuccess(data);
                        }
                    }

                    @Override
                    public void onFailure(Request request, IOException e) {
                        if (callback != null) {
                            callback.onFailure(e);
                        }
                    }
                });
    }

    private void requestInfoByAccountNo(final String accountNo, String token, final HttpCallback<AnalystData> callback) {
        String url = ConfigUtil.instance().getHttpUrlIp(ConfigType.CHAT_URL_TAG) + "/api/user/getUserInfoByAccountNo";
        new Https(url)
                .addParam("accountNo", accountNo)
                .addParam("appsecret", ConfigUtil.instance().mConfigObject.optString(ConfigType.CHAT_APPSECRET))
                .addParam("token", token)
                .get(new Https.ResponseCallback<String>() {
                    @Override
                    public void onSuccess(Request request, Response response, String result, int code) {
                        AnalystData data = parse(result, accountNo, true);
                        if (callback != null) {
                            callback.onSuccess(data);
                        }
                    }

                    @Override
                    public void onFailure(Request request, IOException e) {
                        if (callback != null) {
                            callback.onFailure(e);
                        }
                    }
                });
    }

    private AnalystData parse(String result, String account, boolean cache) {
        if (TextUtils.isEmpty(result)) {
            return null;
        }
        try {
            JSONObject json = new JSONObject(result);
            JSONObject dataJson = json.optJSONObject("data");
            if (dataJson != null) {
                AnalystData data = new AnalystData();
                data.account = account;
                data.userNo = dataJson.optString("userNo");
                data.userName = dataJson.optString("userName");
                data.avatar = dataJson.optString("avatar");
                data.winRate = dataJson.optString("winRate");
                data.gain = dataJson.optString("gain");
                data.position = dataJson.optString("position");
                data.introduction = dataJson.optString("introduction");
                if (cache) {
                    CacheUtils.writeFile(getCacheFile(data.userNo), result);
                }

                return data;
            }
        } catch (JSONException e) {
            Logger.e("", e);
        }
        return null;
    }

    private String getCacheFile(String account) {
        return "discuss_analyst_info_" + account + ".dat";//之所以把斜杠/换成下划线_,是因为写入文件的代码中，
        // 是因为有可能 创建文件时发生错误（某些系统不能越过文件夹直接创建文件，必须先有指定目录，再才能在这个目录下创建文件）
    }

    public class AnalystData {
        String account;
        String userNo;
        String userName;
        String avatar;
        String winRate;
        String gain;
        String position;
        String introduction;
    }

}
